<?php


namespace App\Services\Core\Curd;


trait SaveService
{
    public function create(array $data)
    {
        return $this->result = $this->model->create($data)->makeHidden($this->hidden);
    }

    public function save(array $data, string $pk = 'id', bool $refreshModel = true)
    {
        # 获取模型
        if ($refreshModel) {
            if (!$this->find($data[$pk])) $this->fail(msg: '目标不存在');
        }
        # 检查数据
        if ($this->result->fill($data)->isDirty()) {
            # 更新
            $this->result->save();
            # 结果
            return $this->result;
        }
        $this->fail(msg: '目标并没有发生变化');
    }

    public function update(array $options, array $data)
    {
        $this->result = $this->model->where($options)->update($data);
        return $this->result;
    }
}
